package com.guanyu.u2cache.expression;

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.expression.EvaluationContext;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Objects;

import static org.springframework.aop.support.AopUtils.getTargetClass;

/**
 * @author zhouyunjian
 * @date 2023/11/14 17:00
 **/
public class GeneratorTransfer {


    public Object generateKey(CacheOperationExpressionEvaluator evaluator, KeyGenerator keyGenerator, String keySpEl, Method method, Object[] args, Object target) {
        // 获取注解上的key属性值
        Class<?> targetClass = getTargetClass(target);
        if (StringUtils.hasText(keySpEl)) {
            EvaluationContext evaluationContext = evaluator.createEvaluationContext(method, args, target, targetClass, CacheOperationExpressionEvaluator.NO_RESULT);
            AnnotatedElementKey methodCacheKey = new AnnotatedElementKey(method, targetClass);
            // 兼容传null值得情况
            Object keyValue = evaluator.key(keySpEl, methodCacheKey, evaluationContext);
            return Objects.isNull(keyValue) ? "null" : keyValue;
        }
        return keyGenerator.generate(target, method, args);
    }
}
